package com.seantone.flutter_plugin;

import android.content.Context;

import androidx.annotation.NonNull;

import com.seantone.utils.LZMASDK;

import org.json.JSONException;
import org.json.JSONObject;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class LzmaFlutterPlugin implements FlutterPlugin, MethodChannel.MethodCallHandler {
    private MethodChannel channel;
    private LZMASDK lzmasdk = new LZMASDK();
    private Context appContent;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
        appContent = binding.getApplicationContext();
        channel = new MethodChannel(binding.getBinaryMessenger(), "qt_7ze_flutter");
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        if (call.method.equals("extractFile")) {
            String jsonStr = call.arguments().toString();
            new Thread(() -> {
                try {
                    JSONObject object = new JSONObject(jsonStr);
                    boolean ret = lzmasdk.extractFile(object.getString("fileName"), object.getString("desPath"));
                    result.success(ret);
                } catch (JSONException e) {
                    result.error("onFaild", e.getMessage(), e);
                }
            }).start();
        } else if (call.method.equals("extractAsset")) {
            new Thread(() -> {
                String jsonStr = call.arguments().toString();
                try {
                    JSONObject object = new JSONObject(jsonStr);
                    boolean ret = lzmasdk.extractAsset(appContent.getAssets(), object.getString("fileName"), object.getString("desPath"));
                    result.success(ret);
                } catch (JSONException e) {
                    result.error("onFaild", e.getMessage(), e);
                }
            }).start();
        } else if (call.method.equals("getLzmaVersion")) {
            result.success(lzmasdk.getLzmaVersion());
        }
    }
}
